<template>
	<el-dialog :title="`将【${data.name}】编目模板添加至`" :visible.sync="visible" width="560px" append-to-body>
		<div class="catalog_wrapper">
			<div class="checkbox">
				<el-checkbox :indeterminate="isIndeterminate" v-model="allChecked" @change="handleCheckboxAllChecked">全选</el-checkbox>
			</div>
			<el-checkbox-group v-model="checkedItem" @change="handleCheckboxChecked">
				<el-checkbox v-for="(item, index) in catalogList" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
			</el-checkbox-group>
		</div>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" @click="visible = false">确定</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	props: {
		value: Boolean,
		data: {
			type: Object,
			default () {
				return {};
			}
		},
		catalogs: {
			type: Array,
			default () {
				return [];
			}
		}
	},
	data() {
		return {
			visible: this.value,

			allChecked: false,
			checkedItem: [],
			isIndeterminate: false
		};
	},
	computed: {
		catalogList() {
			return this.catalogs.filter((item) => item.id !== this.data.id);
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if(!flag) return false;
		}
	},
	methods: {
		handleCheckboxAllChecked(flag) {
			this.checkedItem = flag ? this.catalogList.map((item) => item.id) : [];
			this.isIndeterminate = false;
		},
		handleCheckboxChecked(data) {
			let checkedCount = data.length;
			this.allChecked = checkedCount === this.catalogList.length;
			this.isIndeterminate = checkedCount > 0 && checkedCount < this.catalogList.length;
		}
	}
};
</script>

<style lang="scss" scoped>
.catalog_wrapper::v-deep {
	width: 100%;
	padding: 0 0 0 10px;

	.el-checkbox {
		display: flex;
		align-items: center;
		padding: 8px 0;
		width: 122px;
		margin: 0 0 0 10px;

		&:nth-child(4n+1) {
			margin-left: 0;
		}
	}

	.el-checkbox__input {
		font-size: 0;
	}

	.el-checkbox__label {
		line-height: 1;
	}

	.el-checkbox-group {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
	}

	.checkbox {
		display: flex;
	}
}
</style>